package com.android.phoenix.bluetooth;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothAssignedNumbers;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;

public class BluetoothService extends Service {

	public boolean threadFlag = true;
	MyThread myThread;
	CommandReceiver cmdReceiver;// 缁ф壙鑷狟roadcastReceiver瀵硅薄锛岀敤浜庡緱鍒癆ctivity鍙戦�佽繃鏉ョ殑鍛戒护
	private BluetoothAdapter mBluetoothAdapter = null;
	private BluetoothSocket btSocket = null;
	private BluetoothHeadset mBluetoothHeadset = null;
	private BluetoothA2dp mBluetoothA2dp = null;
	private BluetoothDevice mBluetoothDevice = null;
	public List<BluetoothDevice> listBluDevice;
	
	private OutputStream outStream = null;
	private InputStream inStream = null;
	public boolean bluetoothFlag = true;

	private PowerManager mPowerManager;
	private PowerManager.WakeLock mWakeLock;
	
	private UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
	private String address; // <==瑕佽繛鎺ョ殑钃濈墮璁惧MAC鍦板潃
	byte[] buffer = new byte[1024];
	
	
	/************** service 鍛戒护 *********/
	public static final String ACTION_CMD_SEND_DEVICE = "com.android.dream.bycecle.bluetooth.action.CMD_SEND_DEVICE";
	public static final String ACTION_CMD_STOP_SERVICE = "com.android.dream.bycecle.bluetooth.action.CMD_STOP_SERVICE";
	public static final String ACTION_CMD_SEND_SDP_DEVICE = "com.android.dream.bycecle.bluetooth.action.ACTION_CMD_SEND_SDP_DEVICE";
	public static final String ACTION_CMD_SYSTEM_EXIT = "com.android.dream.bycecle.bluetooth.action.CMD_SYSTEM_EXIT";
	public static final String ACTION_CMD_SHOW_TOAST = "com.android.dream.bycecle.bluetooth.action.CMD_SHOW_TOAST";
	public static final String ACTION_CMD_DEVICE_DISCOVERING = "com.android.dream.bycecle.bluetooth.action.CMD_DEVICE_DISCOVERING";
	public static final String ACTION_CMD_DEVICE_CONNECTED = "com.android.dream.bycecle.bluetooth.action.CMD_DEVICE_CONNECTED";
	public static final String ACTION_CMD_DEVICE_DISCONNECTED = "com.android.dream.bycecle.bluetooth.action.CMD_DEVICE_DISCONNECTED";
	public static final String ACTION_CMD_RECEIVE = "com.android.dream.bycecle.bluetooth.action.CMD_RECEIVE";
	public static final String CMD = "com.android.dream.bycecle.bluetooth.cmd";
	public static final String MSGTOAST = "com.android.dream.bycecle.bluetooth.msg.toast";


	private static BluetoothService instance;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		mBluetoothAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.HEADSET);
		mBluetoothAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.A2DP);
		mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
		mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Bicycle");
		mWakeLock.acquire();
		registerReceiver(cmdReceiver, getIntentFilter());
		instance = this;
		return;
	}

	public static BluetoothService getInstance() {
		return instance;
	}

	// 鍓嶅彴Activity璋冪敤startService鏃讹紝璇ユ柟娉曡嚜鍔ㄦ墽
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		address = intent.getStringExtra("Device");
		if (null != address) {
			connectDevice();
		} else {
			mBluetoothAdapter.startDiscovery();
			loopCmd(ACTION_CMD_DEVICE_DISCOVERING);
		}
		return super.onStartCommand(intent, flags, startId);
	}

	public void getSupport() {
		doJob();// 璋冪敤鏂规硶鍚姩绾跨▼
	}
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		this.unregisterReceiver(cmdReceiver);// 鍙栨秷娉ㄥ唽鐨凜ommandReceiver
		threadFlag = false;
		boolean retry = true;
		while (retry) {
			try {
				myThread.join();
				retry = false;
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		mWakeLock.release();
	}

	public class MyThread extends Thread {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();

			while (threadFlag) {
				int value = readByte();
				if (value != -1) {
					loopData(ACTION_CMD_RECEIVE, buffer);					
				}
			}
		}
	}
	public void doJob() {
		if (!mBluetoothAdapter.isEnabled()) {
			bluetoothFlag = false;
			stopService();
			loopData(ACTION_CMD_SHOW_TOAST,"璇锋墦寮�钃濈墮骞堕噸鏂拌繍琛岀▼搴忥紒");
			return;
		}
		threadFlag = true;
		myThread = new MyThread();
		myThread.start();

	}

	public void connectDevice(BluetoothDevice dev) {
		if(null==btSocket)
		{
			try {
				btSocket = dev.createInsecureRfcommSocketToServiceRecord(MY_UUID);
			} catch (IOException e) {
				bluetoothFlag = false;
			}
			if(mBluetoothAdapter.isDiscovering())
			mBluetoothAdapter.cancelDiscovery();
			try {
				btSocket.connect();
				bluetoothFlag = true;
			} catch (IOException e) {
				try {
					btSocket.close();
					bluetoothFlag = false;
				} catch (IOException e2) {

				}
			}

			if (bluetoothFlag) {
				try {
					inStream = btSocket.getInputStream();
				} catch (IOException e) {
					e.printStackTrace();
				} // 缁戝畾璇绘帴锟�
				try {
					outStream = btSocket.getOutputStream();
				} catch (IOException e) {
					e.printStackTrace();
				} // 缁戝畾鍐欐帴锟�

			}
			if (threadFlag) {
				loopCmd(ACTION_CMD_DEVICE_CONNECTED);
			} else {
				loopCmd(ACTION_CMD_DEVICE_DISCONNECTED);
			}
			getSupport();
		}
		
	}

	public void connectDevice() {
		BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
		try {
			btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
		} catch (IOException e) {
			bluetoothFlag = false;
		}
		mBluetoothAdapter.cancelDiscovery();
		try {
			btSocket.connect();
			bluetoothFlag = true;
		} catch (IOException e) {
			try {
				btSocket.close();
				bluetoothFlag = false;
			} catch (IOException e2) {

			}
		}

		if (bluetoothFlag) {
			try {
				inStream = btSocket.getInputStream();
			} catch (IOException e) {
				e.printStackTrace();
			} // 缁戝畾璇绘帴锟�
			try {
				outStream = btSocket.getOutputStream();
			} catch (IOException e) {
				e.printStackTrace();
			} // 缁戝畾鍐欐帴锟�

		}
		if (threadFlag) {
			loopCmd(ACTION_CMD_DEVICE_CONNECTED);
		} else {
			loopCmd(ACTION_CMD_DEVICE_DISCONNECTED);
		}
	}
	public void sendCmd(byte cmd, int value)// 涓插彛鍙戦�佹暟锟�
	{
		if (!bluetoothFlag) {
			return;
		}
		byte[] msgBuffer = new byte[5];
		msgBuffer[0] = cmd;
		msgBuffer[1] = (byte) (value >> 0 & 0xff);
		msgBuffer[2] = (byte) (value >> 8 & 0xff);
		msgBuffer[3] = (byte) (value >> 16 & 0xff);
		msgBuffer[4] = (byte) (value >> 24 & 0xff);

		try {
			outStream.write(msgBuffer, 0, 5);
			outStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public int readByte() {// return -1 if no data
		int ret = -1;
		if (!bluetoothFlag) {
			return ret;
		}

		try {
			ret = inStream.read(buffer);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ret;
	}

	public void stopService() {// 鍋滄鏈嶅姟
		threadFlag = false;// 鍋滄绾跨▼
		stopSelf();// 鍋滄鏈嶅姟
	}
 /**
  *Data:2015/2/2
  * @
  */
	private IntentFilter getIntentFilter()
	{
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(BluetoothHeadset.ACTION_VENDOR_SPECIFIC_HEADSET_EVENT);
		intentFilter.addCategory(BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_COMPANY_ID_CATEGORY+"."+Integer.toString(BluetoothAssignedNumbers.PLANTRONICS));
		intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
		intentFilter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
		intentFilter.addAction(ACTION_CMD_STOP_SERVICE);
		intentFilter.addAction(ACTION_CMD_SEND_DEVICE);
		intentFilter.addAction(ACTION_CMD_SEND_SDP_DEVICE);
		return intentFilter;
	}
	public void loopData(String action, String msg) {// 鏄剧ず鎻愮ず淇℃伅
		Intent intent = new Intent();
		intent.putExtra(MSGTOAST, msg);
		intent.setAction(action);
		sendBroadcast(intent);
	}
	public void loopData(String action, byte[] msg) {// 鏄剧ず鎻愮ず淇℃伅
		Intent intent = new Intent();
		intent.putExtra(MSGTOAST, msg);
		intent.setAction(action);
		sendBroadcast(intent);
	}
	public void loopCmd(String cmd) {
		Intent intent = new Intent();
		intent.setAction(cmd);
		sendBroadcast(intent);
	}
	private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() { 
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
        	
        	if (profile == BluetoothProfile.HEADSET) {     		
        		mBluetoothHeadset = (BluetoothHeadset) proxy; 
                List<BluetoothDevice> connectedDevices = proxy.getConnectedDevices();
                for (BluetoothDevice device : connectedDevices) {
                	mBluetoothDevice = device;         	            	
                }
               int connectionState = mBluetoothHeadset.getConnectionState(mBluetoothDevice);           
               if (connectionState == BluetoothHeadset.STATE_CONNECTED) {
                	Intent mIntent = new Intent();
                	mIntent.setAction(BluetoothService.ACTION_CMD_SEND_SDP_DEVICE);
                	Bundle b = new Bundle();
                	b.putParcelable("Device", mBluetoothDevice);
                	mIntent.putExtras(b);
                	sendBroadcast(mIntent);
            	} else if (connectionState == BluetoothHeadset.STATE_DISCONNECTED) {
            		if (mBluetoothA2dp != null) {

            		}
            	else {

            		}
    			}
            }
        	
        	if (profile == BluetoothProfile.A2DP) {
        		mBluetoothA2dp = (BluetoothA2dp) proxy;
        		List<BluetoothDevice> connectedDevices = proxy.getConnectedDevices();
                for (BluetoothDevice device : connectedDevices) {
                	mBluetoothDevice = device;         	            	
                }
                int connectionState = mBluetoothA2dp.getConnectionState(mBluetoothDevice);
         
                if (connectionState == BluetoothHeadset.STATE_CONNECTED){

            	} else if (connectionState == BluetoothA2dp.STATE_DISCONNECTED){
            	
            		if (mBluetoothHeadset != null)
            		{
            			
            		} else {

            		}
    			}
        	}
        } 
        
        public void onServiceDisconnected(int profile) { 
            if (profile == BluetoothProfile.HEADSET) { 
                mBluetoothHeadset = null; 
            } 
            if (profile == BluetoothProfile.A2DP) { 
          
            	mBluetoothA2dp = null; 
            } 
        } 
    };
	// 鎺ユ敹Activity浼犻�佽繃鏉ョ殑鍛戒护
	private class CommandReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(ACTION_CMD_STOP_SERVICE)) {
				stopService();
			}
			if (intent.getAction().equals(ACTION_CMD_SEND_DEVICE)) {
				address = intent.getStringExtra("Device");
				connectDevice();
			}
			if (intent.getAction().equals(ACTION_CMD_SEND_SDP_DEVICE))
			{
				connectDevice((BluetoothDevice)intent.getExtras().getParcelable("Device"));
			}
		}
	}


}
